package ar.com.duam.porky.movil.tasks;

import static ar.com.duam.porky.movil.ConstantesPorky.URL_PORKY;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.util.Log;

public class LoginTask extends AsyncTask<String, Void, Boolean> 
{

	@SuppressLint("DefaultLocale") @Override
	protected Boolean doInBackground(String... params) 
	{
		String username = params[0];
		String password = params[1];
		
		HttpURLConnection urlConnection = null;
		Boolean success = false;
		
		try 
		{
			URL url = new URL(URL_PORKY +"/login_service?username="+ username +"&password="+ password);
			urlConnection = (HttpURLConnection) url.openConnection();
		
			BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			String response = readFromBuffer(br);
			
			Log.d("login", "Respuesta del web service: "+ response.toString());
			
			success = response.toString().toLowerCase().equals("true");
		}
		catch (Exception ex)
		{
			Log.e("login", ex.getMessage(), ex);
		}
		finally 
		{
			urlConnection.disconnect();
		}
		
		return success;
	}

	private String readFromBuffer(BufferedReader br) throws IOException
	{
		StringBuilder text = new StringBuilder();
		
		String line = br.readLine();
		
		while (line != null) 
		{
			text.append(line);
			
			line = br.readLine();
			
			if (line != null)
			{
				text.append("\n");
			}
		}
		
		return text.toString();
	}
	
}
